/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ru.miit.elearning.servlets;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import ru.miit.elearning.hibernate.dao.CourseDAO;
import ru.miit.elearning.hibernate.dao.HibernateUtil;
import ru.miit.elearning.hibernate.dao.UserDAO;
import ru.miit.elearning.hibernate.dao.WebLabUtil;
import ru.miit.elearning.hibernate.dto.CurriculumLevel;
import ru.miit.elearning.hibernate.dto.UserIdentity;

/**
 *
 * @author Cyclone
 */
public class AddUserServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        String message = new String();

        Session session = null;
        try {
            String lastname = request.getParameter("lastname").trim();
            String firstname = request.getParameter("firstname").trim();
            String email = request.getParameter("email").trim();
            String password = request.getParameter("pass");

            session = HibernateUtil.getSessionFactory().getCurrentSession();
            session.beginTransaction().begin();

            UserDAO userDAO = new UserDAO(session);
            if (userDAO.findUserIdByLogin(email) != null) {
                if (session != null && session.isOpen()) {
                    session.getTransaction().rollback();
                }

                System.err.println("E-mail \"" + email + "\" already used");
                getServletContext().setAttribute("message", "Введённый e-mail уже зарегистрирован в системе");
                response.sendRedirect("Users");
                return;
            }

            List<Integer> profileTypeList = null;
            if (request.isUserInRole("admin")) {
                profileTypeList = new ArrayList<Integer>();
                try {
                    Enumeration<String> parameters = request.getParameterNames();
                    while (parameters.hasMoreElements()) {
                        try {
                            String parameter = parameters.nextElement();
                            String splitter = "group_";
                            if (parameter.split(splitter).length == 2 && request.getParameter(parameter).equals("on")) {
                                profileTypeList.add(Integer.parseInt(parameter.split(splitter)[1]));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    if (!request.isUserInRole("admin")) {
                        System.err.println("Группа не выбрана");
                        System.err.println(e.getLocalizedMessage());

                        message += "<p>Произошла ошибка выбора группы нового пользователя</p>";

                        request.setAttribute("message", message);
                        getServletContext().getRequestDispatcher("/Users").forward(request, response);
                    }
                }
            }

            /*
            session = HibernateUtil.getSessionFactory().getCurrentSession();
            session.beginTransaction().begin();

            UserDAO userDAO = new UserDAO(session);
             */

            UserIdentity userIdentity = null;
            if (request.isUserInRole("admin")) {
                userIdentity = userDAO.addUser(email, password, firstname, lastname, profileTypeList);
            } else {
                if (request.isUserInRole("tutor")) {
                    userIdentity = userDAO.addStudent(email, password, firstname, lastname);
                }
            }
            message += "<p>Пользователь " + userIdentity.getName() + " зарегистрирован : <a href=\"Profile?id=" + userIdentity.getAccount() + "\">профиль</a></p>";
            if ((request.isUserInRole("admin") && profileTypeList.contains(new Integer(UserDAO.PROFILE_TYPE_STUDENT)))
                    || request.isUserInRole("tutor") && !request.isUserInRole("admin")) {
                String courseIdString = request.getParameter("course");
                if (courseIdString != null) {
                    courseIdString = courseIdString.trim();
                    int courseId = Integer.parseInt(courseIdString);
                    if (courseId != -1) {
                        CourseDAO courseDAO = new CourseDAO(session);
                        CurriculumLevel course = courseDAO.signStudentOnCourse(userIdentity.getAccount(), courseId);
                        message += "<p>Произведено зачисление на курс \"<a href='Course?id=" + courseId + "' title='Подробнее о курсе'>" + course.getTitle() + "</a>\".</p>";
                    }
                }
            }

            if (session != null && session.isOpen()) {
                session.getTransaction().commit();
            }

            getServletContext().setAttribute("message", message);
            response.sendRedirect("Users");
        } catch (NoSuchAlgorithmException e) {
            if (session != null && session.isOpen()) {
                session.getTransaction().rollback();
            }
            Logger.getLogger(AddUserServlet.class.getName()).log(Level.SEVERE, null, e);
            e.printStackTrace();


            message = "<p>Ошибка шифрования пароля. Пожалуйста, сообщите администратору.";
            message += WebLabUtil.prepareExceptionRef(request.getSession(), e);
            message += "</p>";
            getServletContext().setAttribute("message", message);

            response.sendRedirect("Users");
        } catch (Exception e) {
            if (session != null && session.isOpen()) {
                session.getTransaction().rollback();
            }

            Logger.getLogger(AddUserServlet.class.getName()).log(Level.SEVERE, null, e);
            e.printStackTrace();

            message = "Произошла ошибка создания пользователя";
            if (e instanceof org.hibernate.exception.DataException) {
//                org.hibernate.exception.DataException de = (org.hibernate.exception.DataException) e;
                message += "<br/>Возможно, одно из полей превосходит разрешённую длину";
            }
            message += WebLabUtil.prepareExceptionRef(request.getSession(), e);
            message += "</p>";
            getServletContext().setAttribute("message", message);

            response.sendRedirect("Users");
        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
